package com.soriya.switcher.config

import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.dataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.floatPreferencesKey
import androidx.datastore.preferences.core.intPreferencesKey
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map

class ConfigRepository(private val context: Context) {

    companion object {
        private val Context.DATA_STORE: DataStore<Preferences> by preferencesDataStore(name = "camera_config")

        private val KEY_VIDEO_PATH = stringPreferencesKey("video_path")
        private val KEY_ROTATE = intPreferencesKey("rotate")
        private val KEY_AUDIO_MODE = intPreferencesKey("audio_mode")
        private val KEY_AUDIO_OUTPUT_VOLUME = floatPreferencesKey("audio_output_volume")
    }

    val config: Flow<CameraConfig> = context.DATA_STORE.data
        .map { preferences ->
            CameraConfig(
                videoPath = preferences[KEY_VIDEO_PATH] ?: "",
                rotate = preferences[KEY_ROTATE] ?: CameraConfig.ROTATE_0,
                audioMode = preferences[KEY_AUDIO_MODE] ?: CameraConfig.AUDIO_MODE_MONITOR_OUTPUT,
                audioOutputVolume = preferences[KEY_AUDIO_OUTPUT_VOLUME] ?: 1F,
            )
        }

    suspend fun updateConfig(update: CameraConfig.() -> CameraConfig) {
        val current = config.first()
        val newConfig = current.update()
        context.DATA_STORE.edit { preferences ->
            preferences[KEY_VIDEO_PATH] = newConfig.videoPath
            preferences[KEY_ROTATE] = newConfig.rotate
            preferences[KEY_AUDIO_MODE] = newConfig.audioMode
            preferences[KEY_AUDIO_OUTPUT_VOLUME] = newConfig.audioOutputVolume
        }
    }

}